package order.demo.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
 * 生成随机验证码
 * @author jon
 *
 */
public class VerifyCode {
	private int width = 70;
	private int height = 35;
	private Random ran = new Random();
	private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"};
	private String codes = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
	//背景颜色
	private Color bgColor = new Color(255, 255, 255);
	//验证码上的文本
	private String text;
	
	/**
	 * 生成随机颜色
	 * @return
	 */
	private Color randomColor() {
		int red = ran.nextInt(150);
		int green = ran.nextInt(150);
		int blue = ran.nextInt(150);
		return new Color(red, green, blue);
	}
	
	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	/**
	 * 生成随机字体，样式，字号
	 */
	private Font randomFont() {
		//1.生成随机字体
		int index = ran.nextInt(fontNames.length);
		String fontName = fontNames[index];
		//2.生成随机样式
		int style = ran.nextInt(4);//0(无样式),1(粗体),2(斜体),3(粗体+斜体)
		//3.生成随机字号
		int size = ran.nextInt(5) + 24;
		return new Font(fontName, style, size);
	}
	
	/**
	 * 画干扰线
	 */
	private void drawLine(BufferedImage image) {
		int num = 3;//三条干扰线
		Graphics2D g2 = (Graphics2D)image.getGraphics();
		for (int i = 0; i < num; i++) {
			int x1 = ran.nextInt(width);
			int x2 = ran.nextInt(width);
			int y1 = ran.nextInt(height);
			int y2 = ran.nextInt(height);
			g2.setStroke(new BasicStroke(1.5F));
			g2.setColor(Color.BLUE);
			//两点坐标画一条直线
			g2.drawLine(x1, y1, x2, y2);
		}
	}
	
	/**
	 * 获取随机一个字节	
	 */
	private char randomChar() {
		int index = ran.nextInt(codes.length());
		return codes.charAt(index);
	}
	
	/**
	 * 生成背景图片
	 */
	private BufferedImage createImage() {
		// 1.创建图片缓存区
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		// 2.得到画笔
		Graphics2D g2 = (Graphics2D)image.getGraphics();
		// 3.设置背景色
		g2.setColor(this.bgColor);
		g2.fillRect(0, 0, width, height);
		return image;
	}
	
	/**
	 * 生成随机验证码
	 * @return
	 */
	public BufferedImage getImage() {
		BufferedImage image = createImage();
		Graphics2D g2 = (Graphics2D)image.getGraphics();
		StringBuilder sb = new StringBuilder();//用来装载生成的文本
		
		for (int i = 0; i < 4; i++) {
			String str = randomChar() + "";//生成一个随机字母
			sb.append(str);//将每个字母添加到sb中
			float x = i * 1.0F * width / 4;//字母位置的横坐标
			g2.setColor(randomColor());
			g2.setFont(randomFont());
			g2.drawString(str, x, height - 5);
		}
		this.text = sb.toString();
		drawLine(image);
		return image;
	}
}
